package com.xcdh.ittools.handler;

import com.xcdh.ittools.mapping.ITToolParameterMapping;
import com.xcdh.ittools.reflection.SimpleMetaObject;
import com.xcdh.ittools.sql.ITToolBoundSql;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class ITToolParameterHandler {


    private ITToolBoundSql boundSql ;

    public ITToolParameterHandler( ITToolBoundSql boundSql) {
        this.boundSql = boundSql;
    }

    public void setParameters(PreparedStatement ps) throws SQLException {
        List<ITToolParameterMapping> parameterMappings = this.boundSql.getParameterMappings();
        if (parameterMappings != null) {
            for (int i = 0; i < parameterMappings.size(); i++) {
                ITToolParameterMapping parameterMapping = parameterMappings.get(i);
                Object value = parameterMapping.getValue();
                TypeHandler typeHandler = parameterMapping.getTypeHandler();
                JdbcType jdbcType = null;
                if (value == null && jdbcType == null) {
                    jdbcType = JdbcType.OTHER;
                }
                try {
                    typeHandler.setParameter(ps, i + 1, value, jdbcType);
                } catch (TypeException | SQLException e) {
                    throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
                }
            }
        }
    }
}
